/*
 * @(#)GenericsUtils.java $Revision: 25 $ $Date: 2009-05-08 11:11:53 +0800 $
 *
 * Copyright (c) 易才集团技术公司.
 */
package com.ctg.payroll2.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.apache.log4j.Logger;

@SuppressWarnings("unchecked")  
public class GenericsUtils {
    private static final Logger log = Logger.getLogger(GenericsUtils.class);

    private GenericsUtils() {
    }

    public static Class getSuperClassGenricType(Class clazz) {
        return getSuperClassGenricType(clazz, 0);
    }

    public static Class getSuperClassGenricType(Class clazz, int index) {
        Type genType = clazz.getGenericSuperclass();
        if (!(genType instanceof ParameterizedType)) {
            log.warn(clazz.getSimpleName() +
                     "'s superclass not ParameterizedType");
            return Object.class;
        }

        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

        if (index >= params.length || index < 0) {
            log.warn("Index: " + index + ", Size of " + clazz.getSimpleName() +
                     "'s Parameterized Type: "
                     + params.length);
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
            log.warn(clazz.getSimpleName() +
                    " not set the actual class on superclass generic parameter");
            return Object.class;
        }
        return (Class) params[index];

    }
}
